package com.utils;

import javax.el.MethodExpression;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.MethodExpressionActionListener;

public class JsfUtils {

	public static MethodExpression createActionExpression(
			String actionExpression, Class<?> returnType) {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		return facesContext
				.getApplication()
				.getExpressionFactory()
				.createMethodExpression(facesContext.getELContext(),
						actionExpression, returnType, new Class[0]);
	}

	public static Object getBeanInstanceFromFacesContext(String beanName) {
		Object object = null;
		if (FacesContext.getCurrentInstance() != null) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			object = facesContext.getApplication().getELResolver()
					.getValue(facesContext.getELContext(), null, beanName);
		}
		return object;
	}
	
	public static MethodExpressionActionListener createActionListener(String actionListenerExpression) {
		FacesContext context = FacesContext.getCurrentInstance();
	    return new MethodExpressionActionListener(context.getApplication().getExpressionFactory()
	        .createMethodExpression(context.getELContext(), actionListenerExpression, null, new Class[] {ActionEvent.class}));
	}
	
	public static void navigateTo(String page){
		FacesContext context = FacesContext.getCurrentInstance();
		NavigationHandler nav = context.getApplication()
				.getNavigationHandler();
		nav.handleNavigation(context, null, page);
	}
}
